package br.com.emmis.tercons;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.analytics.tracking.android.EasyTracker;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

import br.com.emmis.tercons.constants.Constants;
import br.com.emmis.tercons.model.Config;


/**
 * A simple {@link android.app.Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link br.com.emmis.tercons.SendingIntentionsFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link br.com.emmis.tercons.SendingIntentionsFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class SendingIntentionsFragment extends Fragment {


    private OnFragmentInteractionListener mListener;

    private static final String ARG_NAME = "ARG_NAME";
    private static final String ARG_CITY = "ARG_CITY";
    private static final String ARG_PRECE = "ARG_PRECE";

    private String mIntentionName;
    private String mIntentionCity;
    private String mIntentionPrece;

    private EasyTracker mEasyTracker;
    private Config mConfig;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment LoadingIntentionsFragment.
     */

    public static SendingIntentionsFragment newInstance(String name, String city, String prece) {
        SendingIntentionsFragment fragment = new SendingIntentionsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_NAME, name);
        args.putString(ARG_CITY, city);
        args.putString(ARG_PRECE, prece);
        fragment.setArguments(args);
        return fragment;
    }
    public SendingIntentionsFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mConfig = Config.getInstance(getActivity().getApplicationContext());
        mEasyTracker = EasyTracker.getInstance(getActivity().getApplicationContext());
        if (getArguments() != null) {
            mIntentionName = getArguments().getString(ARG_NAME);
            mIntentionCity = getArguments().getString(ARG_CITY);
            mIntentionPrece = getArguments().getString(ARG_PRECE);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        mEasyTracker.activityStop(getActivity());
    }

    @Override
    public void onStart() {
        super.onStart();
        mEasyTracker.activityStart(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        SendingIntentionsTask loadIntentionsTask = new SendingIntentionsTask();
        loadIntentionsTask.execute(mIntentionName, mIntentionCity, mIntentionPrece);

        return inflater.inflate(R.layout.fragment_loading_intentions, container, false);
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        public void onSendingOk();
        public void onSendingError();
    }

    private class SendingIntentionsTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPostExecute(String result) {
			if(mListener == null) {
				return;
			}
            if(result != null && result.contains("OK")) {
				mListener.onSendingOk();
            } else {
                mListener.onSendingError();
            }
        }

        @Override
        protected String doInBackground(String... strings) {

            String line = "FAIL";
            String nome = strings[0];
            String city = strings[1];
            String prece = strings[2];
			String idioma = mConfig.getmLocation();
			String email = mConfig.getmUserEmail();
            String url = mConfig.getmIntentionURL() + Constants.SEND_INTENTIONS_URL;
            String appId = mConfig.getmApp();
            String configs = mConfig.toString();

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
                nameValuePairs.add(new BasicNameValuePair(Constants.XML_NODE_NOME, nome));
                nameValuePairs.add(new BasicNameValuePair(Constants.XML_NODE_CITY, city));
                nameValuePairs.add(new BasicNameValuePair(Constants.XML_NODE_PRECE, prece));
				nameValuePairs.add(new BasicNameValuePair(Constants.XML_NODE_IDIOMA, idioma));
                nameValuePairs.add(new BasicNameValuePair(Constants.XML_NODE_APP, appId));
				nameValuePairs.add(new BasicNameValuePair(Constants.XML_NODE_EMAIL, email));
                nameValuePairs.add(new BasicNameValuePair(Constants.XML_NODE_CONFIGS, configs));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                line = EntityUtils.toString(httpEntity);


            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return line;
            }
        }

    }

}
